package com.lyz.collectionDemo.collectionSet;

import java.util.Comparator;
import java.util.Set;
import java.util.TreeSet;

/**
 * @ClassName SetDemo2
 * @Description TreeSet
 * @Author 2214361854
 * @Date 2022/2/21 21:16
 * @Version 1.0
 */
public class SetDemo2 {
    public static void main(String[] args) {
        Set<Integer> sets = new TreeSet<>();
        sets.add(1);
        sets.add(12);
        sets.add(14);
        sets.add(21);
        System.out.println(sets);
        System.out.println("=====================");
        //升序规则：
        //认为左边大返回正整数
        //认为右边大返回负整数
        //两数相等返回0
        //Double.compare() 比较两个double


        //方式2
//        Set<Apple> apples = new TreeSet<>(new Comparator<Apple>() {
//            @Override
//            public int compare(Apple o1, Apple o2) {
//                return o1.getWeight()-o2.getWeight() >= 0?1:1;
//            }
//        });

        //方式2 简写
        Set<Apple> apples = new TreeSet<>((o1, o2) -> o1.getWeight()-o2.getWeight() >= 0?1:1);
        apples.add(new Apple("苹果","红色",12.5,500));
        apples.add(new Apple("香蕉","黄色",11.5,100));
        apples.add(new Apple("荔枝","黄色",14.2,200));
        apples.add(new Apple("栗子","褐色",13.7,400));
        System.out.println(apples);
    }
}
class Apple implements Comparable<Apple>{
    private String name;
    private String color;
    private double price;
    private int weight;

    @Override
    public String toString() {
        return "Apple{" +
                "name='" + name + '\'' +
                ", color='" + color + '\'' +
                ", price=" + price +
                ", weight=" + weight +
                '}';
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public int getWeight() {
        return weight;
    }

    public void setWeight(int weight) {
        this.weight = weight;
    }

    public Apple(String name, String color, double price, int weight) {
        this.name = name;
        this.color = color;
        this.price = price;
        this.weight = weight;
    }

    public Apple() {
    }

    /**
     * 方式一、类自定义比较规则
     * @param o
     * @return
     */
    @Override
    public int compareTo(Apple o) {
        return this.weight-o.weight >= 0 ? 1 : -1;
    }
}
